import { aiStudyApi, safeIndexApi } from '@/api';
import CusModal from '@/components/CusModal';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd';
import { Button, Card, Cascader, Collapse, Form, Input, InputNumber, message, Select, Space, Table } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';
import SelAiModal from '../../component/SelAiModal';
import SelectObj from '../../component/SelectObjNew';

export interface AddEditPorps {
  aiPlanId?: string;
  cover?: string;
  onBack?(): void;
  title?: string;
  learnEndTime?: string;
  learnStartTime?: string;
}

type FormValue = {
  aiPlanId?: string;
  // coursewares?: Source[];
  title?: string;
  studyTime?: number;
  cover?: UploadFile[];
  // studyObject?: number;
  // timerRange: [dayjs.Dayjs, dayjs.Dayjs];
};
let collapseItemsData: any = [];
let studyObjectType = 1;
const { PaneItem } = YmAddPageLayout;
export function AddEdit({ onBack, aiPlanId, title, cover, learnEndTime, learnStartTime }: AddEditPorps) {
  //   const [itemProps] = CategoryCascader.useFieldLevelTwo(classId && parClassId ? [parClassId, classId] : undefined);
  const sutdyTimeOptions = [
    {
      value: 12,
      label: '12小时',
    },
    {
      value: 24,
      label: '24小时',
    },
    {
      value: 48,
      label: '48小时',
    },
    {
      value: 72,
      label: '72小时',
    },
  ];
  const objOptions = [
    {
      value: 1,
      label: '协会',
    },
    {
      value: 2,
      label: '企业',
    },
  ];
  const [form] = Form.useForm<FormValue>();
  const [modalOpen, setModalOpen] = useState<number>();
  const [objType, setObjType] = useState<number>(1);
  // const [objModelOpen, { setTrue, setFalse }] = useBoolean();
  const [isModalShow, setIsModalShow] = useState<{ show: boolean; type?: string; modelType?: string }>({ show: false });
  const [configModal, setConfigModal] = useState<{ title: string; children: React.ReactNode }>();
  const [modalBtnStatus, setModalBtnStatus] = useState({ loading: false, disabled: false }); //modal框按钮状态
  // const [eventList, setEventList] = useState<any[]>([]);
  const [eventOptions, setEventOptions] = useState<any[]>([]);
  const [collapseItems, setCollapseItems] = useState<any[]>([]); // 折叠面板列表
  const [seledObjArr, setSeledObjArr] = useState<any[]>([]); // 已选的对象
  const [seledNum, setSeledNum] = useState<number>(0);
  let [collaKey, setcollaKey] = useState<number>(0);
  let [keytwo, setkeytwo] = useState<number>(0);
  let [colNum, setColNum] = useState<number>(0);
  let [colInputNum, setColInputNum] = useState<number>(0);
  const [activeCol, setActiveCol] = useState<any[]>(['0']);
  const SelectObjRef = useRef<any>(null);
  const SelAiModalRef = useRef<any>(null);

  const [initValue] = useState<FormValue>(() => {
    return {
      cover: cover ? [{ url: cover, uid: cover, name: cover }] : [],
      title,
    };
  });
  // 保存表单
  // const { run, loading } = useRequest(aiStudyApi.addAiPlanTask, {
  //   manual: true,
  //   onSuccess() {
  //     onBack?.();
  //   },
  // });
  const pubPlan = (aiPlanId: any) => {
    aiStudyApi.switchStatus({ aiPlanId, openStatus: 1 }).then((res: any) => {
      if (res.code == 200) onBack?.();
    });
  };
  // 保存计划 type 1保存 2发布
  const savePlan = (params: any, type: number) => {
    aiStudyApi.addAiPlanTask(params).then((res: any) => {
      console.log(res);
      if (res.code == 200) {
        if (type == 1) {
          onBack?.();
        } else {
          pubPlan(res.data);
        }
      }
    });
  };

  const customRequest = useYmAliOss();
  // 关闭modal
  const closeModal = () => {
    setIsModalShow({ show: false });
  };
  // 获取选择的企业/协会人数
  const getObjPersonNum = (values: any) => {
    console.log(values, '打印看看数据');
    const entIdsArr = values.map((el: any) => {
      return el.entId;
    });
    aiStudyApi.getObjPersonNum({ entIds: entIdsArr.join(','), type: objType }).then((res: any) => {
      setSeledNum(res.data);
    });
  };

  const selAiStudyCont = (param: any) => {
    const { type } = param;
    console.log(param, '打印看看选择的参数');
    // setModalType('matter');
    setIsModalShow({ show: true, type, modelType: 'selAiCont' });
    setConfigModal({
      title: '选择AI学习内容',
      children: <SelAiModal ref={SelAiModalRef} {...param} />,
    });
  };
  const columns = [
    {
      title: (
        <div>
          <span style={{ color: '#ff4d4f', marginRight: 5 }}>*</span>
          <span>触发条件次数</span>
        </div>
      ),
      dataIndex: 'startNumber',
      key: 'startNumber',
      render: (text: any, record: any) => (
        <>
          <InputNumber
            value={text}
            style={{ width: 60 }}
            min={1}
            max={99}
            precision={0}
            controls={false}
            onChange={(e) => {
              collapseItemsData.forEach((el: any, index1: any) => {
                if (index1 == record.parIndex) {
                  el.aiStudyTriggerVoList.forEach((item: any, index2: any) => {
                    // 对当前行处理
                    if (index2 == record.index) {
                      // 如果在非第一行，并且值<=上一行的start,则开始置为上一行的start+1
                      if (index2 != 0 && e <= el.aiStudyTriggerVoList[index2 - 1].startNumber)
                        item.startNumber = el.aiStudyTriggerVoList[index2 - 1].startNumber + 1;
                      else item.startNumber = e;
                      // 如果在非第一行，则上一行的end为当前行的start
                      if (index2 != 0) el.aiStudyTriggerVoList[index2 - 1].endNumber = item.startNumber;
                    }
                  });
                }
              });
              setColInputNum(++colInputNum);
            }}
          />
          ≤次数
          {record.endNumber && record.endNumber != 999999999 ? (
            <>
              {/* <Input value={record.endNumber} style={{ width: 60 }} /> */}
              <span style={{ display: 'inline-block', width: 100 }}>＜{record.endNumber}</span>
            </>
          ) : null}
        </>
      ),
    },
    {
      title: (
        <div>
          <span style={{ color: '#ff4d4f', marginRight: 5 }}>*</span>
          <span>AI学习内容</span>
        </div>
      ),
      dataIndex: 'classId',
      key: 'classId',
      render: (text: any, record: any) => (
        <a>
          <Input
            value={record.classId ? '课件包/' + record.parentClassName + '/' + record.className : ''}
            style={{ width: 200 }}
            onClick={() => {
              selAiStudyCont({ type: 'add', record });
            }}
          />
        </a>
      ),
    },
    {
      title: (
        <div>
          <span style={{ color: '#ff4d4f', marginRight: 5 }}>*</span>
          <span>学习内容数量</span>
        </div>
      ),
      dataIndex: 'studyNumber',
      key: 'studyNumber',
      render: (text: any) => (
        <a>
          <Input value={1} style={{ width: 60 }} disabled />
        </a>
      ),
    },
    {
      title: '',
      dataIndex: 'index',
      key: 'index',
      render: (text: any, record: any) => {
        const dealDada = () => {
          setColNum(++colNum);
        };
        if (record.isLast == 1 && text == 0)
          return (
            <PlusOutlined
              onClick={(e) => {
                e.stopPropagation();
                if (collapseItemsData[record.parIndex].aiStudyTriggerVoList.length >= 5)
                  return message.error('最多只能添加五条');
                collapseItemsData[record.parIndex].aiStudyTriggerVoList.push({
                  startNumber: '',
                  endNumber: '',
                  classId: '',
                  type: 1,
                  studyNumber: 1,
                });
                dealDada();
              }}
            />
          );
        if (record.isLast == 1 && text !== 0)
          return (
            <>
              <PlusOutlined
                onClick={(e) => {
                  e.stopPropagation();
                  if (collapseItemsData[record.parIndex].aiStudyTriggerVoList.length >= 5)
                    return message.error('最多只能添加五条');
                  collapseItemsData[record.parIndex].aiStudyTriggerVoList.push({
                    startNumber: '',
                    endNumber: '',
                    classId: '',
                    type: 1,
                    studyNumber: 1,
                  });
                  dealDada();
                }}
              />
              <CloseOutlined
                onClick={(e) => {
                  e.stopPropagation();
                  collapseItemsData[record.parIndex].aiStudyTriggerVoList.pop();
                  dealDada();
                }}
              />
            </>
          );
      },
    },
  ];

  // arr转为渲染的表格
  const setColldata = (type = 1) => {
    collapseItemsData.forEach((el: any, index1: any) => {
      el.aiStudyTriggerVoList.forEach((item: any, index2: any) => {
        item.index = index2;
        item.isLast = index2 + 1 === el.aiStudyTriggerVoList.length ? 1 : 0;
        item.parIndex = index1;
        if (!item.parentClassName) item.parentClassName = '';
        if (!item.className) item.className = '';
        if (item.isLast == 1) item.endNumber = '999999999';
      });
    });
    const arr = collapseItemsData.map((el: any, index: any) => {
      let aaaaa = [];
      aaaaa = el.aiStudyTriggerVoList;
      console.log('---------eventOptions------', eventOptions);
      el.cascaTitle = el.groupName && el.factorName ? [el.groupName, el.factorName] : [];
      return {
        key: index,
        label: (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <span style={{ color: '#ff4d4f', marginRight: 5 }}>*</span>
              <Cascader
                style={{ width: 250 }}
                key={keytwo}
                options={eventOptions}
                placeholder="请选择违规事项"
                onClick={(e) => {
                  e.stopPropagation();
                  // 点击时候，所有已选择的，给他禁用状态
                  eventOptions.forEach((el: any) => {
                    el.children.forEach((item: any) => {
                      // let a = false;
                      // collapseItemsData.forEach((obj: any) => {
                      //   console.log(obj.code, item.value, obj.factorName, '打印看看');
                      //   if (obj.code === item.value) a = true;
                      // });
                      // if (a) item.disabled = true;
                      // else item.disabled = false;
                      // 选项的禁用取决于是否在已有数组里有相同code 上面的简写
                      item.disabled = collapseItemsData.some((obj: any) => {
                        return obj.code === item.value;
                      });
                    });
                  });
                }} // 阻止冒泡
                onChange={(e, value) => {
                  collapseItemsData.forEach((el: any, index1: any) => {
                    if (index1 == index) {
                      // 清空时候，value会undefined
                      if (value) {
                        el.groupName = value[0].label;
                        el.factorName = value[1].label;
                        el.code = value[1].value;
                      } else {
                        el.groupName = '';
                        el.factorName = '';
                        el.code = '';
                      }
                      el.sort = index;
                    }
                  });
                  setColldata();
                }}
                // multiple // 多选
                maxTagCount="responsive"
                // defaultValue={['驾驶陋习', '抽烟']}
                defaultValue={el.cascaTitle}
              />
            </div>
            <a
              onClick={(e) => {
                e.stopPropagation();
                collapseItemsData.splice(index, 1);
                setkeytwo(++keytwo);
                setColldata();
              }} // 阻止冒泡
            >
              删除条件
            </a>
          </div>
        ),
        // key 每次增加行、删除行，列表要自动更新
        children: <Table dataSource={aaaaa} key={index + colNum} columns={columns} pagination={false} />,
      };
    });
    setCollapseItems(arr);
    if (type == 1) {
      // setcollaKey(++collaKey); // 不需要每次重新渲染折叠列表。所以注释
    }
  };
  // 点击modal保存按钮
  const confirmModal = () => {
    setModalBtnStatus({ disabled: true, loading: true });
    if (SelectObjRef.current) {
      SelectObjRef.current
        ?.onSubmit()
        .then((values: any) => {
          console.log(values, '打印一下下');
          setSeledObjArr([...values]);
          closeModal();
          getObjPersonNum(values);
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
      setModalBtnStatus({ disabled: false, loading: false });
    } else if (SelAiModalRef.current) {
      SelAiModalRef.current
        ?.onSubmit()
        .then((values: any) => {
          if (values) {
            collapseItemsData.forEach((el: any, index1: any) => {
              if (index1 == values.record.parIndex) {
                el.aiStudyTriggerVoList.forEach((item: any, index2: any) => {
                  if (index2 == values.record.index) {
                    item.parentClassName = values.record.parentClassName;
                    item.className = values.record.className;
                    item.classId = values.record.classId;
                  }
                });
              }
            });

            setColldata();
            closeModal();
            // getObjPersonNum(values);
          }
        })
        .finally(() => {
          setModalBtnStatus({ disabled: false, loading: false });
        });
      setModalBtnStatus({ disabled: false, loading: false });
    }

    // addOrEditFactorRef.current
    //   ?.onSubmit()
    //   .then((values: any) => {
    //     if (!values) return;
    //     addOrEditFactorApi(values);
    //   })
    //   .finally(() => {
    //     setModalBtnStatus({ disabled: false, loading: false });
    //   });
    // setModalBtnStatus({ disabled: false, loading: false });
  };
  // modal框配置
  const modalConst = {
    open: isModalShow.show,
    width: 730,
    centered: true,
    destroyOnClose: true,
    footer: [
      <Button key="back" disabled={modalBtnStatus.disabled} onClick={closeModal}>
        取消
      </Button>,
      <Button type="primary" key="save" loading={modalBtnStatus.loading} onClick={confirmModal}>
        确定
      </Button>,
    ],
    onCancel: closeModal,
  };

  // 选择学习对象
  const openObj = (param: any) => {
    const { type } = param;
    // setModalType('matter');
    const ids = seledObjArr.map((el) => el.entId).join(',');
    setIsModalShow({ show: true, type, modelType: 'matter' });
    setConfigModal({
      title: type === 'add' ? '选择学习对象' : '选择学习对象',
      children: <SelectObj ref={SelectObjRef} {...param} />,
    });
  };

  // 获取事项触发条件级联列表
  const getEventsList = () => {
    safeIndexApi.getMatterGropList({ relatedType: 3 }).then((res: any) => {
      const resdata = res.data;
      // setEventList(resdata);
      const newArr = resdata.map((el: any) => {
        return {
          label: el.groupName,
          value: el.groupId,
          children: el.safetyFactorDetailVoList.map((item: any) => {
            return { label: item.factorName, value: item.code };
          }),
        };
      });
      // 新增时候，
      newArr.forEach((el: any) => {
        el.children.forEach((item: any) => {
          // let a = false;
          // collapseItemsData.forEach((obj: any) => {
          //   console.log(obj.code, item.value, obj.factorName, '打印看看');
          //   if (obj.code === item.value) a = true;
          // });
          // if (a) item.disabled = true;
          // else item.disabled = false;
          // 选项的禁用取决于是否在已有数组里有相同code 上面的简写
          item.disabled = collapseItemsData.some((obj: any) => {
            return obj.code === item.value;
          });
        });
      });
      // eventOptions = [...newArr];
      console.log('------newArr-----', newArr);
      setEventOptions([...newArr]);
      // keytwo = keytwo + 1;
      setkeytwo(++keytwo);
    });
  };

  useEffect(() => {
    if (eventOptions) {
      console.log(aiPlanId, '计划id');

      // setTimeout(() => {
      let resdata: any[] = [];
      // eslint-disable-next-line no-constant-condition
      if (aiPlanId) {
        aiStudyApi.getAiDetail({ aiPlanId: aiPlanId }).then((res: any) => {
          console.log(res.data, '打印看看详情');
          const val = res.data;
          form.setFieldsValue({ title: val.title, studyTime: val.studyTime });
          if (val.cover) form.setFieldsValue({ cover: [{ url: val.cover, uid: val.cover, name: val.cover }] });
          setObjType(val.studyObject);
          setSeledObjArr(val.entList);
          resdata = res.data.aiStudyRuleVoList;
          collapseItemsData = [...resdata];
          setSeledNum(val.planPersonNum);
          setColldata();
        });
      } else {
        resdata = [
          {
            groupName: '',
            factorName: '',
            code: '',
            sort: '',
            aiStudyTriggerVoList: [
              {
                startNumber: '',
                endNumber: '999999999',
                classId: '',
                type: 1,
                studyNumber: 1,
              },
            ],
          },
        ];
        collapseItemsData = [...resdata];
        setColldata();
      }
      // }, 0);
    }
  }, [eventOptions]);

  useEffect(() => {
    getEventsList();
  }, []);
  // 添加触发规则
  const addRuleDto = () => {
    collapseItemsData.push({
      groupName: '',
      factorName: '',
      code: '',
      sort: '',
      aiStudyTriggerVoList: [
        {
          startNumber: '',
          endNumber: '',
          classId: '',
          type: 1,
          studyNumber: 1,
        },
      ],
    });
    setColNum(++colNum);
    const arr = activeCol;
    // for (let i = 0; i <= collapseItemsData.length; i++) {
    //   arr.push(i.toString());
    // }
    const a = collapseItemsData.length - 1;
    arr.push(a.toString());
    // ActiveCol.push();
    setActiveCol(arr);
    setcollaKey(++collaKey);
  };
  useEffect(() => {
    if (colNum) {
      setColldata(1);
    }
  }, [colNum]);
  useEffect(() => {
    if (colInputNum) {
      setColldata(2);
    }
  }, [colInputNum]);
  // 判断是否有空课件包的分类
  const getIfhasVoid = (params: any, type: number) => {
    aiStudyApi.getAiContList({}).then((res: any) => {
      if (res.code == 200) {
        const resdata = res.data.list;
        console.log(resdata, res, '打印看看分类');
        // 把没有内容的分类id抛出来，然后遍历搞
        const arr: any[] = [];
        resdata.forEach((el: any) => {
          el.lowerListVo.forEach((item: any) => {
            if (item.canChoose == 0) arr.push(item.guid);
          });
        });
        for (let i = 0; i < collapseItemsData.length; i++) {
          if (!collapseItemsData[i].code) return message.error('第' + (i + 1) + '个触发条件请选择违规事项');
          for (let key = 0; key < collapseItemsData[i].aiStudyTriggerVoList.length; key++) {
            if (!collapseItemsData[i].aiStudyTriggerVoList[key].startNumber)
              return message.error('第' + (i + 1) + '个触发条件的第' + (key + 1) + '条规则请输入次数');
            if (!collapseItemsData[i].aiStudyTriggerVoList[key].classId)
              return message.error('第' + (i + 1) + '个触发条件的第' + (key + 1) + '条规则请选择学习内容');
            if (arr.includes(collapseItemsData[i].aiStudyTriggerVoList[key].classId))
              return message.error('第' + (i + 1) + '个触发条件的第' + (key + 1) + '条规则的学习内容的分类没有资源');
          }
        }
        params.aiStudyRuleDtoList = [...collapseItemsData];
        params.aiStudyRuleDtoList.forEach((item: any) => {
          item.aiStudyTriggerDtoList = [...item.aiStudyTriggerVoList];
          item.aiStudyTriggerDtoList?.forEach((el: any) => {
            delete el.index;
            delete el.isLast;
            delete el.parIndex;
          });
          delete item.aiStudyTriggerVoList;
        });
        if (aiPlanId) params.aiPlanId = aiPlanId;
        // if (params.coursewares.length === 0) {
        //   message.error('请选择学习内容');
        // }
        // params.aiStudyRuleDtoList.forEach((el: any) => {
        //   console.log(el, '打印看看');
        // });
        // console.log(params, '打印看看form表单');
        // run(params);
        savePlan(params, type);
      }
    });
  };
  // 保存
  const save = async (type: number) => {
    const { cover: _cover, ...value } = await form.validateFields();
    if (seledObjArr.length < 1) return message.error('请选择学习对象');
    // console.log(await form.validateFields(), '打印看看渠道的表单对象');
    // console.log(objType, collapseItemsData, '看看对象值');
    const params: any = {
      // courseId,
      studyObject: objType,
      planPersonNum: seledNum,
      entList: [...seledObjArr],
      cover: _cover?.map((v) => v.response || v.url).join(','),
      ...value,
    };
    if (collapseItemsData.length == 0) return message.error('请至少有一个触发条件');
    getIfhasVoid(params, type);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="save" type="default" size="small" onClick={() => save(1)}>
        保存
      </Button>,
      <Button key="publish" type="primary" size="small" onClick={() => save(2)}>
        发布
      </Button>,
    ];
    return operationBtn;
  }, [seledObjArr]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          onBack?.();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label={aiPlanId ? '编辑AI学习计划' : '添加AI学习计划'} className="pane_tab1">
        <div>
          <div style={{ height: '100%', overflow: 'auto' }}>
            <Form form={form} labelCol={{ style: { width: 100 } }} initialValues={initValue}>
              <Card title="基础信息" style={{ marginBottom: 16 }}>
                <Form.Item label="计划名称" name="title" rules={[{ required: true }]} style={{ marginBottom: 24 }}>
                  <Input showCount maxLength={18}></Input>
                </Form.Item>
                <Form.Item label="学习时间" name="studyTime" rules={[{ required: true }]} style={{ marginBottom: 24 }}>
                  <Select placeholder="请选择" options={sutdyTimeOptions} style={{ width: 100 }} />
                </Form.Item>
                <Form.Item label="">
                  <div style={{ display: 'inline-block', marginRight: 5, marginLeft: 20 }}>
                    <span style={{ color: '#ff4d4f', marginRight: 3, marginLeft: 5 }}>*</span>
                    <span>学习对象:</span>
                  </div>
                  <Select
                    placeholder="请选择"
                    value={objType}
                    options={objOptions}
                    style={{ width: 150 }}
                    onChange={(value) => {
                      setObjType(value);
                      studyObjectType = value;
                      setSeledObjArr([]);
                      setSeledNum(0);
                    }}
                  />
                  <Input
                    placeholder="请选择"
                    style={{ width: 200, marginLeft: 15, cursor: 'pointer' }}
                    onClick={() => {
                      openObj({
                        type: 'add',
                        objtype: objType,
                        ids: seledObjArr.map((el) => el.entId).join(','),
                        objs: JSON.stringify(seledObjArr),
                      });
                    }}
                    value={seledObjArr.length > 0 ? seledObjArr.length + '家' : ''}
                  />
                  {seledObjArr.length > 0 ? <>共{seledNum}人</> : null}
                </Form.Item>
                <Form.Item label="封面图">
                  <Space size={20}>
                    <Form.Item name="cover" noStyle rules={YmUpload.formRules(false)}>
                      <YmUpload maxCount={1} cardWidth={375} cardHeight={200} customRequest={customRequest}>
                        请上传封面
                      </YmUpload>
                    </Form.Item>
                    <div>
                      <p>图片仅支持jpg、png格式 </p>
                      <p> 图片大小750*400 </p>
                    </div>
                  </Space>
                </Form.Item>
              </Card>
              <Card
                title="AI学习规则"
                extra={
                  <Button
                    type="primary"
                    shape="round"
                    onClick={() => {
                      // setModalOpen(Math.random());
                      addRuleDto();
                    }}
                  >
                    添加触发条件
                  </Button>
                }
              >
                <Form.Item name="aiStudyRuleDtoList" noStyle>
                  <Collapse
                    // 这里会导致每次添加，自动其他折叠,后期这里做成可控动态的
                    defaultActiveKey={activeCol}
                    key={collaKey}
                    onChange={(e) => {
                      setActiveCol(Array.isArray(e) ? e : JSON.parse(e));
                    }}
                    // expandIconPosition={expandIconPosition}
                    items={collapseItems}
                  />
                </Form.Item>
              </Card>
            </Form>
          </div>
          <CusModal {...modalConst} {...configModal} />
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}
